package com.wx.springboot.step5.service.impl;

import com.wx.springboot.step5.common.api.ResultCode;
import com.wx.springboot.step5.exception.ApiAssert;
import com.wx.springboot.step5.service.AuthCodeService;
import com.wx.springboot.step5.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * 验证码管理Service实现类
 */
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE; // 验证码前缀

    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS; // 验证码有效期，单位：秒

    @Override
    public String generateAuthCode(String telephone) {
        if (StringUtils.isBlank(telephone)) {
            ApiAssert.failed(ResultCode.VALIDATE_FAILED);
        }
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        String authCode = sb.toString();
        //验证码绑定手机号并存储到redis,超过有效期作废
        String key = REDIS_KEY_PREFIX_AUTH_CODE + telephone;
        redisService.set(key, authCode, AUTH_CODE_EXPIRE_SECONDS);
        return authCode;
    }


    @Override
    public void verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isBlank(telephone) || StringUtils.isBlank(authCode)) {
            ApiAssert.failed("请输入验证码");
        }
        String key = REDIS_KEY_PREFIX_AUTH_CODE + telephone;
        String realAuthCode = redisService.get(key);
        if (!authCode.equals(realAuthCode)) {
            ApiAssert.failed("验证码不正确，或者已失效");
        }
        redisService.remove(key); // 验证码已经校验成功，移除缓存
    }

}
